﻿/*
 * Erstellt mit SharpDevelop.
 * Benutzer: inffbr
 * Datum: 07.05.2009
 * Zeit: 13:43
 * 
 *
 */
using ProviderHandler;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Net;

namespace XtraZonePlugin
{
	/// <summary>
	/// Xtra-Zone
	/// </summary>
	public class XtraZone : ProviderHandler.IWebSMSHandler
	{
		private WebRequester requester;
		private string URL;
		
		public void Initialize()
		{
			requester = new WebRequester();
			requester.TimeOut = 10000;
			URL = "https://xtrazone.sso.bluewin.ch/index.php/22,39,ajax_json,,,157/";
		}
		
		public string Name {
			get {
				return "Xtra-Zone 2.0";
			}
		}
		public string Author {
			get {
				return "Florian (thx to theduckking & scream)";
			}
		}
		public string Version
		{
			get
			{
				return BlackXS.Info.AssemblyInfo.AssemblyVersion;
			}
		}
		public string Description {
			get {
				return "SMS provider for the new Swisscom Xtra Zone";
			}
		}
		public string Provider {
			get {
				return "Swisscom";
			}
		}
		public string ProviderHomepage {
			get {
				return "http://swisscom-mobile.ch";
			}
		}
		public Bitmap ProviderLogo {
			get {
				return XtraZonePlugin.Properties.Resources.logo_swisscom;
			}
		}
		
		public string LoginName {get; set;}
		public string Password  {get; set;}
		
		public bool Login()
		{
            if (IsLoggedIn())
            {
                return true;
            }
            else
            {
                if (Password.ToLower() == "token")
                {
                    return this.LoginWithToken();
                }
                else
                {
                    string CaptchaData = "action=getCaptcha&token=&do_sso_login=0&sso_user=" + this.LoginName + "&sso_password=" + this.Password + "&passphrase=";
                    String html = requester.PostRequest(URL, "", CaptchaData);

                    string picUri = "http://" + Cut(html, "img\":\"\\/\\/", "\",\"uri").Replace("\\", "");
                    string tokenid = Cut(html, "token\":\"", "\",\"img");

                    frmChaptchaHandler cpHandler = new frmChaptchaHandler(tokenid, picUri);

                    if (cpHandler.ShowDialog() == DialogResult.OK)
                    {
                        string LoginData = "action=ssoLogin&token=" + cpHandler.TokenID + "&do_sso_login=1&sso_user=" + this.LoginName + "&sso_password=" + this.Password + "&passphrase=" + cpHandler.CaptchaString;
                        html = requester.PostRequest(URL, "", LoginData);
                    }
                    else
                    {
                        return false;
                    }

                    if (html.Contains("login_ok"))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
			
		}
		
		private bool IsLoggedIn()
		{
			string ProfileURI = "https://xtrazone.sso.bluewin.ch/index.php/20?route=%2Fprofile";
			string html = requester.GetRequest(ProfileURI, ProfileURI);
            if (html.Contains("Auf diese Inhalte kannst Du nicht zugreifen."))
			{
				return false;
			}
			else
			{
				return true;
			}
		}
		
		public bool SendSMS(string receiver, string message)
		{
			string SendSMSURL = "https://xtrazone.sso.bluewin.ch/index.php/20,53,ajax,,,283/?route=%2Fmessaging%2Foutbox%2Fsendmobilemsg";
			string SMSSendData = "receiversnames=" + receiver + "&recipients=%5B%5D&messagebody=" + message + "&attachments=&attachmentId=";
			string html = requester.PostRequest(SendSMSURL, SendSMSURL, SMSSendData);
			if (html.Contains("Verarbeitung erfolgreich"))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		
		public int SMSLength {
			get {
				return 440;
			}
		}
		
		public string SMSAdvertisement
		{
			get{return "\n- sent by xtrazone.ch";}
		}
		
		public ProviderHandler.Contact[] GetContacts()
		{
			List<ProviderHandler.Contact> clist = new List<ProviderHandler.Contact>();
			string GetContactURI = "https://xtrazone.sso.bluewin.ch/index.php/20?route=%2Fmessaging";
			string html = requester.GetRequest(GetContactURI, GetContactURI);

			html = Regex.Replace(html, "\t", "");
			html = Cut(html, "<div class=\"userdata\">", "<hr class=\"trenner small\" />");
			
			Contact currentContact = new Contact();

			string[] lines = html.Split("\r\n".ToCharArray());
			
			foreach (String line in lines)
			{
				if (line.StartsWith("    <h5>"))
				{
					currentContact = new Contact(sEmit.AsciiEditing.AsciitoChars(Cut(line, "<h5>", "</h5>")), "");
				}
				else if (line.StartsWith("    <p>"))
				{
					currentContact.Number = sEmit.AsciiEditing.AsciitoChars(Cut(line, "<p>", "</p>"));
					if (currentContact.Name != string.Empty)
					{
						clist.Add(currentContact);
					}
				}
			}
			
			return clist.ToArray();
		}
		public bool AddContact(string name, string number)
		{
			string addContactURI = "https://xtrazone.sso.bluewin.ch/index.php/20,53,ajax,,,283/?route=%2Fprofile%2Fcontact%2Faddcontact&refresh=/profile/contact/list";
			string AddContactData = "prename=" + name + "&name=&natelnr=" + number + "&contactId=&save=Speichern";
			string html = requester.PostRequest(addContactURI, addContactURI, AddContactData);
			
			if (html.Contains("Kontakt gespeichert."))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		public bool DeleteContact(string name, string number)
		{
			string DeleteURI = "https://xtrazone.sso.bluewin.ch/index.php/20,53,ajax,,,283/?route=%2Fprofile%2Fcontact%2Fdeletecontact&refresh=/profile/contact/contactsanchors";
			string DeleteContactData = ("id=" + GetContactID(name, number).Replace(":", "%3A"));
			string html = requester.PostRequest(DeleteURI, DeleteURI, DeleteContactData);

            if (html.Contains("Kontakt gel"))
            {
                return true;
            }
            else
            {
                return false;
            }
		}
		
		private string GetContactID(string name, string number)
		{
			if (number.StartsWith("0"))
			{
				number = "41" + number.Remove(0, 1);
			}
			
			string GetContactURI = "https://xtrazone.sso.bluewin.ch/index.php/20?route=%2Fmessaging";
			string html = requester.GetRequest(GetContactURI, GetContactURI);

			html = Regex.Replace(html, "\t", "");
			html = Cut(html, number + "</p>", "<div class=\"userdata\">");
			
			string[] lines = html.Split("\r\n".ToCharArray());
			
			foreach (String line in lines)
			{
				if (line.StartsWith("<input"))
				{
					return Cut(line, "value=\"", "\"");
				}
			}
			
			return "nouserfound";
		}
		
		public ProviderHandler.AccountInformation GetInformation()
		{
			ProviderHandler.AccountInformation ai = new ProviderHandler.AccountInformation();

            string reqURI = "https://xtrazone.sso.bluewin.ch/index.php/20,51,ajax,,,283/?route=%2Flogin%2Fuserboxinfo";
			string html = requester.GetRequest(reqURI, reqURI);

            html = Cut(html, "class=\\\"userinfo\\\">", "class=\\\"inbox\\\">");
			
			ai.AccountName = sEmit.AsciiEditing.AsciitoChars(Cut(html, "<h6><a href=\\\"\\/index.php\\/20?route=%2Fprofile\\\">", "<\\/a>"));

            string leftsms = Cut(html, "<em>Guthaben bis ", "&nbsp;MMS");

            ai.LeftSMS = Convert.ToInt32(leftsms.Remove(0, 19));
            ai.Special = sEmit.AsciiEditing.AsciitoChars(Cut(html, "\\t\\t\\t<h5>", "<\\/h5>\\n"));
			ai.MaxSMS = 500;

			return ai;
		}
		
		private string Cut(string html, string before, string after)
		{
			string temp = html.Remove(0, html.IndexOf(before) + before.Length);
			temp = temp.Remove(temp.IndexOf(after));
			return temp;
		}
		
		private bool LoginWithToken()
		{
            frmTokenHandler tokenhandler = new frmTokenHandler();
			if (GetToken())
			{
				
				DialogResult dr = tokenhandler.ShowDialog();
				
				if (dr == DialogResult.OK)
				{
					string token = tokenhandler.Token;
					string LoginData = "action=natel_token_form&page=2&sso_natel=" + LoginName + "&sso_token=" + token;
					string html =  requester.PostRequest(URL, "https://xtrazone.sso.bluewin.ch/index.php/21/de/home_private", LoginData);
					
					if (html.Contains("login_ok"))
					{
						return true;
					}
					else
					{
						return false;
					}
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}
		
		private bool GetToken()
		{
			string LoginData = "action=natel_token_form&page=1&sso_natel=" + LoginName + "&sso_token=";
			string html =  requester.PostRequest(URL, "https://xtrazone.sso.bluewin.ch/index.php/21/de/home_private", LoginData);
			
			if (html.Contains("request_ok"))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
}